package com.google.code.customercare.login;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.code.customercare.common.BaseAction;
import com.google.code.customercare.common.Constants;
import com.google.code.customercare.model.autogen.User;
import com.google.code.customercare.model.ext.HibernateUtil;
import com.google.code.customercare.model.ext.MyUserDao;

public class LoginAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private MyUserDao dao;
	private static Logger log = Logger.getLogger("customercare-access");
	
	public LoginAction() {
		dao = new MyUserDao();
	}
	
	public String execute() {
		try{
			username = username.trim();
			password = password.trim();
			log.info(toString());
			// hash passwd truoc khi xac thuc
			//List list = dao.findByUserNameAndPasswd(username, PasswordService.encrypt(password));
			List list = dao.findByUserNameAndPasswd(username, password);
			if(list != null && list.size() > 0) {
				User user = (User)list.get(0);
				getSession().put(Constants.USER_KEY, username);
				getSession().put(Constants.ID_KEY, user.getId());
				log.info("successful login");
				setDestination("home");
				return SUCCESS;	
			}else{
				log.info("retry login");
				setMessage("Xin bạn thử lại");
				return "fail";
			}
		}catch(Exception e){
			log.error("exception login", e);
			setMessage("Xin bạn thử lại");
			return "fail";
		}finally{
			try {
				HibernateUtil.closeSession();
			} catch (Exception e) {
				log.error("exception in close session", e);
			}
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String toString() {
		return "LoginAction [username=" + username + ", password=" + password
				+ "]";
	}

	@Override
	protected boolean checkToken() {
		return false;
	}

	@Override
	protected void rememberToken() {
		
	}
}
